//
//  YPBaseTableView.m
//  project
//
//  Created by 姚敦鹏 on 2018/10/13.
//  Copyright © 2018年 rocHome. All rights reserved.
//

#import "YPBaseTableView.h"

#define EmptyTitleColor HEXColor(0x666666)
#define EmptyTipColor   HEXColor(0x999999)

@interface YPBaseTableView ()

@property (nonatomic,assign) BOOL isPullUp;
@property (nonatomic,assign) BOOL isPullDown;

@property (nonatomic,copy) NSArray *normalImages;
@property (nonatomic,copy) NSArray *refreshImages;

//@property (nonatomic,strong) UIImageView *gifImageView;
//@property (nonatomic,strong) UIView      *loadingView;
//@property (nonatomic,strong) UILabel     *loadingTip;
@end

@implementation YPBaseTableView

- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style isPullUp:(BOOL)isPullUp isPullDown:(BOOL)isPullDown {
    
    if (self = [super initWithFrame:frame style:style]) {
        [self setEmptyDelegate];
        [self setIsPullDown:isPullDown withIsPullUp:isPullUp];
    }
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame isPullUp:(BOOL)isPullUp isPullDown:(BOOL)isPullDown {
    
    if (self = [super initWithFrame:frame]) {
        [self setEmptyDelegate];
        [self setIsPullDown:isPullDown withIsPullUp:isPullUp];
    }
    return self;
}

#pragma mark -- empty
- (void)setEmptyDelegate {
    
    self.emptyDataSetSource   = self;
    self.emptyDataSetDelegate = self;
    
    // 删除单元格分隔线
    self.tableFooterView = [UIView new];
}

-(void)setIsPullDown:(BOOL)isPullDown
        withIsPullUp:(BOOL)isPullUp
{
    self.isPullUp   = isPullUp;
    self.isPullDown = isPullDown;
    [self YPPullRefreshInit];
}

- (void)YPPullRefreshInit {
    
    if (self.isPullDown) {
        MJRefreshGifHeader *gifHeader = [MJRefreshGifHeader headerWithRefreshingBlock:^{

            // 重置没有更多
            self.mj_footer ? [self.mj_footer resetNoMoreData] : nil;
            self.pullDownBlock ? self.pullDownBlock(self) : [self pullRefreshEnd];
        }];
        self.mj_header = gifHeader;
        [gifHeader setImages:self.normalImages forState:MJRefreshStateIdle];
        [gifHeader setImages:self.refreshImages forState:MJRefreshStatePulling];
        // 设置正在刷新状态的动画图片
        [gifHeader setImages:self.refreshImages forState:MJRefreshStateRefreshing];
        self.mj_header.automaticallyChangeAlpha = YES;
    } else {
        self.mj_header = nil;
    }
    
    if (self.isPullUp) {
        MJRefreshBackGifFooter *footerFooter = [MJRefreshBackGifFooter footerWithRefreshingBlock:^{
            self.pullUpBlock ? self.pullUpBlock(self) : [self pullRefreshEnd];
        }];
        self.mj_footer = footerFooter;
        [footerFooter setImages:self.normalImages forState:MJRefreshStateIdle];
        [footerFooter setImages:self.refreshImages forState:MJRefreshStatePulling];
        // 设置正在刷新状态的动画图片
        [footerFooter setImages:self.refreshImages forState:MJRefreshStateRefreshing];
        
        self.mj_footer.automaticallyChangeAlpha = YES;
    } else {
        self.mj_footer = nil;
    }
}

- (void)pullRefreshEnd {
    
    [self.mj_header endRefreshing];
    [self.mj_footer endRefreshing];
}

- (void)pullRefreshNotMore {

    [self.mj_header endRefreshing];
    [self.mj_footer endRefreshingWithNoMoreData];
}

- (void)setPullDownBlock:(PullBlock)pullDownBlock
         withPullUpBlock:(PullBlock)pullUpBlock
{
    self.pullDownBlock = pullDownBlock;
    self.pullUpBlock   = pullUpBlock;
}

#pragma mark -- DZNEmptyDataSetSource
// 空白页显示图片
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    
    UIImage *emptyImage = IMAGENANED(@"emptyNothing");
    if ([YPReachability shareInstall].isHasNet) {
        switch (self.emptyStatus) {
            case YPPageEmptyStatusError:
                emptyImage = IMAGENANED(@"emptyError");
                break;
            case YPPageEmptyStatusNoData:
                emptyImage = IMAGENANED(@"emptyNothing");
                break;
            default:
                emptyImage = IMAGENANED(@"emptyNoNet");
                break;
        }
    } else {
        emptyImage = IMAGENANED(@"emptyNoNet");
    }
    return emptyImage;
}

// 空白页显示标题
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *title = @"暂无数据";
    if ([YPReachability shareInstall].isHasNet) {
        switch (self.emptyStatus) {
            case YPPageEmptyStatusError:
                title = @"页面开小差了";
                break;
            case YPPageEmptyStatusNoData:
                title = @"暂无数据";
                break;
            default:
                title = @"网络走丢了";
                break;
        }
    } else {
        title = @"网络走丢了";
    }
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0f],
                                 NSForegroundColorAttributeName:EmptyTitleColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

// 空白页显示详细描述
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSString *text = @"点击重新加载";
    if ([YPReachability shareInstall].isHasNet) {
        switch (self.emptyStatus) {
            case YPPageEmptyStatusError:
                text = @"网络繁忙，请稍候再试";
                break;
            case YPPageEmptyStatusNoData:
                text = @"点击重新加载";
                break;
            default:
                text = @"检查您的网络或点击重新加载";
                break;
        }
    } else {
        text = @"检查您的网络或点击重新加载";
    }
    
    NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:14.0f],
                                 NSForegroundColorAttributeName:EmptyTipColor,
                                 NSParagraphStyleAttributeName:paragraph
                                 };
    
    return [[NSAttributedString alloc] initWithString:text attributes:attributes];
}

#pragma mark -- DZNEmpty Delegate
- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView {
    
    return self.emptyStatus != YPPageEmptyStatusLoading && self.emptyStatus != YPPageEmptyStatusHidden;
}

-(CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -kNavigationBarH;
}

-(BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView {
    return YES;
}

-(void)emptyDataSet:(UIScrollView *)scrollView didTapView:(UIView *)view {
    self.emptyTapBlock ? self.emptyTapBlock(self) : nil;
}

#pragma mark -- 点击 tableView 响应
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
        [_touchDelegate respondsToSelector:@selector(tableView:touchesBegan:withEvent:)])
    {
        [_touchDelegate tableView:self touchesBegan:touches withEvent:event];
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesCancelled:touches withEvent:event];
    
    if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
        [_touchDelegate respondsToSelector:@selector(tableView:touchesCancelled:withEvent:)])
    {
        [_touchDelegate tableView:self touchesCancelled:touches withEvent:event];
    }
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesEnded:touches withEvent:event];
    
    if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
        [_touchDelegate respondsToSelector:@selector(tableView:touchesEnded:withEvent:)])
    {
        [_touchDelegate tableView:self touchesEnded:touches withEvent:event];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesMoved:touches withEvent:event];
    
    if ([_touchDelegate conformsToProtocol:@protocol(TouchTableViewDelegate)] &&
        [_touchDelegate respondsToSelector:@selector(tableView:touchesMoved:withEvent:)])
    {
        [_touchDelegate tableView:self touchesMoved:touches withEvent:event];
    }
}

//#pragma mark -- Loading
//- (void)setLoadingFrame {
//
//    [self.loadingView addSubview:self.gifImageView];
//    [self.gifImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.size.mas_equalTo(CGSizeMake(50, 50));
//        make.center.mas_equalTo(CGPointMake(self.loadingView.center.x, self.loadingView.center.y - 20));
//    }];
//
//    [self.loadingView addSubview:self.loadingTip];
//    [self.loadingTip mas_makeConstraints:^(MASConstraintMaker *make) {
//
//        make.top.mas_equalTo(self.gifImageView.mas_bottom).offset(kMargin+5);
//        make.left.mas_equalTo(kMargin);
//        make.right.mas_equalTo(-kMargin);
//    }];
//}
//
//#pragma mark -- Getter
//-(NSArray *)normalImages {
//
//    if (_normalImages == nil) {
//
//        _normalImages = [NSArray array];
//        // 设置普通状态的动画图片
//        NSMutableArray *normalImags = [NSMutableArray array];
//        for (NSUInteger i = 1; i <= 60; i++) {
//            UIImage *image = [UIImage imageNamed:@"refresh_1"];
//            [normalImags addObject:image];
//        }
//        _normalImages = normalImags;
//    }
//    return _normalImages;
//}
//
//-(NSArray *)refreshImages {
//
//    if (_refreshImages == nil) {
//
//        _refreshImages = [NSArray array];
//        // 设置即将刷新状态的动画图片（一松开就会刷新的状态）
//        NSMutableArray *refreshingImages = [NSMutableArray array];
//        for (NSUInteger i = 1; i <= 7; i++) {
//            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"refresh_%zd", i]];
//            [refreshingImages addObject:image];
//        }
//        _refreshImages = refreshingImages;
//    }
//    return _refreshImages;
//}
//
//-(UIImageView *)gifImageView {
//
//    if(_gifImageView == nil) {
//        NSArray *magesArray = [NSArray arrayWithObjects:
//                               [UIImage imageNamed:@"loading1.png"],
//                               [UIImage imageNamed:@"loading2.png"],
//                               [UIImage imageNamed:@"loading3.png"],
//                               [UIImage imageNamed:@"loading4.png"],
//                               [UIImage imageNamed:@"loading5.png"],
//                               [UIImage imageNamed:@"loading6.png"],
//                               [UIImage imageNamed:@"loading7.png"],
//                               [UIImage imageNamed:@"loading8.png"],
//                               [UIImage imageNamed:@"loading9.png"],
//                               nil];
//        _gifImageView = [UIImageView new];
//        _gifImageView.animationImages = magesArray;
//        _gifImageView.animationDuration = 0.6;
//        _gifImageView.animationRepeatCount = 0;
//        [_gifImageView startAnimating];
//    }
//    return _gifImageView;
//}
//
//-(UIView *)loadingView{
//    if(_loadingView == nil){
//        _loadingView = [UIView new];
//    }
//    return _loadingView;
//}
//
//-(UILabel *)loadingTip {
//
//    if (_loadingTip == nil) {
//        _loadingTip               = [UILabel new];
//        _loadingTip.textColor     = HEXColor(0x333333);
//        _loadingTip.font          = [UIFont systemFontOfSize:16.0f];
//        _loadingTip.text          = @"Loading...";
//        _loadingTip.numberOfLines = 1;
//        _loadingTip.textAlignment = NSTextAlignmentCenter;
//    }
//    return _loadingTip;
//}

@end
